package top.xiaoazi.futureletterserver.module.letter.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.xiaoazi.futureletterserver.common.R;
import top.xiaoazi.futureletterserver.module.letter.entity.Letter;
import top.xiaoazi.futureletterserver.module.letter.entity.LetterBug;
import top.xiaoazi.futureletterserver.module.letter.service.LetterService;
import top.xiaoazi.futureletterserver.module.letter.vo.LetterCountOnCurUserVO;
import top.xiaoazi.futureletterserver.module.letter.vo.LetterSentVO;
import top.xiaoazi.futureletterserver.utils.*;

import java.sql.Timestamp;
import java.util.*;


@RestController
@RequestMapping("/letter")
public class LetterController {
    @Autowired
    private CryptoAESUtils cryptoAESUtils;

    @Autowired
    private DataValidatorUtils dataValidatorUtils;

    @Autowired
    private RequestUtils requestUtils;

    @Autowired
    private LetterService letterService;

    @Autowired
    private UserUtils userUtils;

    /**
     * 校验信件内容是否合法
     * @param letter
     * @return
     * @throws Exception
     */
    private Boolean isLegal(Letter letter) throws Exception {

        // 解密
        String content = cryptoAESUtils.decrypt(letter.getContent());
        String title = cryptoAESUtils.decrypt(letter.getTitle());
        Document doc = Jsoup.parse(content); // 转换成html
        String plainText = doc.text(); // 去掉html标签

        // 如果出现违禁词, 表示不合法
        if(dataValidatorUtils.isForbidden(plainText) || dataValidatorUtils.isForbidden(title)) {
            return false;
        }
        return true;
    }

    /**
     * 测试接口, 前端不调用, 测试信件内容是否合法
     * @param letter
     * @return
     */
    @PostMapping("/is-legal")
    public R isOk(@RequestBody Letter letter) {
        List<String> list = Arrays.asList(DataValidatorUtils.words);
        Set<String> set = new HashSet<>();
        Collections.addAll(set, list.toArray(new String[0]));

        String content = letter.getContent();
        content = content.replaceAll(" ", "");
        content = content.replaceAll("&nbsp;", "");

        List<String> res = new ArrayList<>();
        for (String word : set) {
            if (content.contains(word)) {
                res.add(word);
            }
        }
        return R.success(res);
    }

    /**
     * 发送定时信件
     * @param letter
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/send")
    public R send(@RequestBody Letter letter, HttpServletRequest request) throws Exception {
        if(!isLegal(letter)) {
            return R.error(201, "在信件中和标题中请文明发言!");
        }
        Integer userId = userUtils.getUserId(request);
        letter.setUserId(userId);
        letter.setState(0); // 0 表示待发送
        letter.setWriteTime(new Timestamp(TimeUtils.currentTimeMillis())); // 设置写信时间
        // 存数据库
        letterService.send(letter);
        Thread.sleep(2000);
        return R.success("定时发送成功", cryptoAESUtils.decrypt(letter.getContent()));
    }

    /**
     * 暂存信件
     * @param letter
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/save")
    public R save(@RequestBody Letter letter, HttpServletRequest request) throws Exception {
        if(!isLegal(letter)) {
            return R.error(201, "在信件中和标题中请文明发言!");
        }

        Integer userId = userUtils.getUserId(request);
        // 如果不是更改信件内容，暂存箱最多保存50封信件
        if (letter.getId() == null && letterService.getCountOnCurUser(userId).getSaveCount() >= 50) {
            return R.success(201, "暂存箱最多保存50封信件哦!");
        }

        letter.setUserId(userId);
        letter.setState(2); // 2 表示暂存信件
        letter.setWriteTime(new Timestamp(TimeUtils.currentTimeMillis())); // 设置写信时间

        // 存数据库
        letterService.send(letter);
        Thread.sleep(2000);
        return R.success("暂存信件成功", cryptoAESUtils.decrypt(letter.getContent()));
    }

    /**
     * 获取已经发送的信件
     * @return
     */
    @GetMapping("/get-sent-info")
    public R getSentInfo(HttpServletRequest request) {
        Integer userId = userUtils.getUserId(request);
        List<LetterSentVO> list = letterService.getSentInfo(userId);
        return R.success(list);
    }

    /**
     * 获取等待发出的信
     * @param request
     * @return
     */
    @GetMapping("/get-waiting-send-info")
    public R getWaitingSendInfo(HttpServletRequest request) {
        Integer userId = userUtils.getUserId(request);
        return R.success(letterService.getWaitingSendInfo(userId));
    }

    /**
     * 获取公开信
     * @param
     * @return
     */
    @GetMapping("/get-sent-and-pub-info")
    public R getSentAndPubInfo() {
        List<Letter> list = letterService.getSentAndPubInfo();
        return R.success(list);
    }

    /**
     * 分页查询
     * @param pageSize
     * @param pageNumber
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/get-sent-and-pub-info-limit")
    public R getSentAndPubInfoLimit(@RequestParam(value = "pagesize")Integer pageSize,
                                    @RequestParam(value = "pagenum")Integer pageNumber) throws InterruptedException {
        Thread.sleep(1000);
        // 计算偏移量
        int offset = (pageNumber - 1) * pageSize; // 假设 pageSize 为5，第一页偏移量为0，第二页偏移量为5，第三页偏移量为 10
        List<Letter> list = letterService.getSentAndPubInfoLimit(pageSize, offset);
        return R.success(list);
    }

    /**
     * 通过Id获取公开信信息
     * @param id
     * @return
     */
    @GetMapping("/get-sent-and-pub-info-by-id")
    public R getSentAndPubInfoById(Integer id) {
        Letter letter = new Letter();
        if (id == null) {
            return R.success("error", letter);
        }
        Letter resLetter = letterService.getSentAndPubInfoById(id);
        return R.success(resLetter);
    }

    /**
     * 获取当前登录用户的已发送的信息，通过 id
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/get-sent-info-by-id")
    public R getSendInfoById(HttpServletRequest request,Integer id) {
        Integer userId = userUtils.getUserId(request);
        LetterSentVO letterSentVO = letterService.getSendInfoById(userId, id);
        return R.success(letterSentVO);
    }

    /**
     * 获取当前登录用户的统计数据
     * @param request
     * @return
     */
    @GetMapping("/get-count-on-cur-user")
    public R getCountOnCurUser(HttpServletRequest request) {
        Integer userId = userUtils.getUserId(request);
        LetterCountOnCurUserVO result = letterService.getCountOnCurUser(userId);
        return R.success(result);
    }

    /**
     * 获取暂存的信件
     */
    @GetMapping("/get-save-info")
    public R getSaveInfo(HttpServletRequest request, @RequestParam(value = "select", required = false) String select) throws Exception {
        Integer userId = userUtils.getUserId(request);
        List<Letter> result = letterService.getSaveInfo(userId, select);
        return R.success(result);
    }

    /**
     * 删除暂存箱里面的信件内容
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/del-save-info")
    public R delSaveInfo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        Integer letterId = (Integer) params.get("id");
        Integer userId = userUtils.getUserId(request);
        boolean result = letterService.delSaveInfo(letterId, userId);
        return R.success(result);
    }

    /**
     * 通过id获取保存的信件
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/get-save-info-by-id")
    public R getSaveInfoById(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        Integer letterId = (Integer) params.get("id");
        Integer userId = userUtils.getUserId(request);
        Letter letter = letterService.getSaveInfoById(letterId, userId);
        return R.success(letter);
    }

    /**
     * 获取个人list页面
     */
    @GetMapping("/get-list")
    public R getList(HttpServletRequest request) {
        Integer userId = userUtils.getUserId(request);
        List<LetterSentVO> list = letterService.getList(userId);
        return R.success(list);
    }

    /**
     * bug反馈
     * @param letterBug
     * @return
     */
    @PostMapping("/submit-bug")
    public R submitBug(@RequestBody LetterBug letterBug) {
        // 检查内容是否有脏字
        if (dataValidatorUtils.isForbidden(letterBug.getContent())) {
            return R.success(201, "反馈失败!");
        }
        letterService.submitBug(letterBug);
        return R.success("已反馈成功, 感谢您的反馈!");
    }

    /**
     * bug获取
     * @return
     */
    @GetMapping("/sys/get-bugs")
    public R getBugs() {
        List<LetterBug> list = letterService.getBugs();
        return R.success(list);
    }

    /**
     * bug获取
     * @return
     */
    @GetMapping("/sys/get-bugs-no-solve")
    public R getBugsNoSolve() {
        List<LetterBug> list = letterService.getBugsNoSolve();
        return R.success(list);
    }

    // 获整个网站待投递的信件
    @GetMapping("/get-waiting-send-count")
    public R getWaitingSendCount() {
        int count = letterService.getWaitingSendCount();
        return R.success(count);
    }

    // 获取整个网站已经投递的信件
    @GetMapping("/get-sent-count")
    public R getSentCount() {
        int count = letterService.getSentCount();
        return R.success(count);
    }

    // 修改已经解决的bug
    @PostMapping("/sys/change-letter-bug")
    public R changeLetterBug(@RequestBody LetterBug letterBug) {
        int a = letterService.changeLetterBug(letterBug);
        return R.success("修改成功");
    }
}
